<script setup lang="ts">
  import { computed, PropType, ref, watch } from 'vue'
  import SingleAddress from '@/components/business/address/single-address/SingleAddress.vue'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import {
    useGetOrderUserInfoBeforeUpdate,
    useUpdateOrderUserInfo,
  } from '@/services/pages/order/useOrder'
  import { FormInstance } from 'element-plus'
  import departmentFixedData from '@/config/fixed-data/department/department'
  import { useGetReplaceCustomers } from './services/useGetReplaceCustomers'

  const {
    info: userInfoBeforeUpdate,
    getInfoLoading: getUserInfoBeforeUpdateLoading,
    getInfo: getUserInfoBeforeUpdate,
  } = useGetOrderUserInfoBeforeUpdate()
  const { updateForm, updateLoading, update, resetForm } = useUpdateOrderUserInfo()
  const {
    replaceCustomers,
    getReplaceCustomersKeyword,
    getReplaceCustomersLoading,
    getReplaceCustomers,
  } = useGetReplaceCustomers()

  defineOptions({
    name: 'UpdateOrderCustomerInfoModal',
  })

  const props = defineProps({
    orderDetail: {
      type: Object as PropType<OrderDetail>,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'update'): void
  }>()

  const productType = computed(() => {
    if (props.orderDetail.departmentId === departmentFixedData.business) {
      return 'business'
    }

    if (props.orderDetail.departmentId === departmentFixedData.family) {
      return 'family'
    }

    return ''
  })
  const visible = defineModel('visible', { type: Boolean, default: false })
  const singleAddressInstance = ref<InstanceType<typeof SingleAddress> | null>(null)
  const formInstance = ref<FormInstance | null>(null)
  const echoAddress = computed(() => {
    return {
      province: updateForm.value.province,
      city: updateForm.value.city,
      area: updateForm.value.area,
      town: updateForm.value.town,
    }
  })
  const rules = ref({
    name: [{ required: true, message: '请输入公司名称', trigger: ['blur', 'change'] }],
  })
  const replaceTablePopoverVisible = ref(false)

  const close = () => {
    if (singleAddressInstance.value) {
      singleAddressInstance.value.clearAddress()
    }
    resetForm()
    visible.value = false
  }

  const onSave = async () => {
    if (formInstance.value) {
      try {
        await formInstance.value.validate()
        const res = await update()
        if (res.code === 20000) {
          visible.value = false
          HMessage.success('修改成功')
          emits('update')
        } else {
          HMessageBox.error(res.message)
        }
      } catch (error) {
        // e
      }
    }
  }

  const handleChangeAddress = (_address: {
    province: string
    city: string
    area: string
    town: string
  }) => {
    updateForm.value.province = _address.province
    updateForm.value.city = _address.city
    updateForm.value.area = _address.area
    updateForm.value.town = _address.town
  }

  const _newCustomerQuery = async () => {
    const res = await getReplaceCustomers()
    if (res) {
      if (res.code !== 20000) {
        HMessageBox.error(res.message)
        return
      }

      if (replaceCustomers.value.length === 1) {
        handleReplaceCustomerClick(replaceCustomers.value[0])
        return
      }

      replaceTablePopoverVisible.value = true
    }
  }

  const handleReplaceCustomerClick = (customer: OrderDetailAPIResponse.ReplaceCustomer) => {
    Object.assign(updateForm.value, {
      name: customer.username,
      province: customer.province,
      city: customer.city,
      area: customer.area,
      address: customer.address,
      userId: customer.userId,
    })
    if (productType.value === 'business') {
      updateForm.value.phone = customer.phone
    } else {
      updateForm.value.businessPhone = customer.phone
    }
    getReplaceCustomersKeyword.value = ''
    replaceTablePopoverVisible.value = false
  }

  watch(
    visible,
    (value) => {
      if (value && props.orderDetail.id) {
        getUserInfoBeforeUpdate(props.orderDetail.id).then(() => {
          updateForm.value = {
            address: userInfoBeforeUpdate.value.address,
            area: userInfoBeforeUpdate.value.area,
            businessPhone: userInfoBeforeUpdate.value.businessPhone,
            city: userInfoBeforeUpdate.value.city,
            helpOtherCreateOrder: 0,
            name: userInfoBeforeUpdate.value.name,
            otherPhone: userInfoBeforeUpdate.value.otherPhone,
            phone: userInfoBeforeUpdate.value.phone,
            province: userInfoBeforeUpdate.value.province,
            repairCompany: '',
            repairCompanyId: '',
            repairCompanyPhone: '',
            sendForRepairPhone: userInfoBeforeUpdate.value.sendForRepairPhone,
            sendForRepairUsername: userInfoBeforeUpdate.value.sendForRepairUsername,
            storeName: userInfoBeforeUpdate.value.storeName,
            town: userInfoBeforeUpdate.value.town,
            userId: '',
            id: props.orderDetail.id,
          }
        })
      }
    },
    { immediate: true },
  )
</script>

<template>
  <h-drawer
    v-model="visible"
    :loading="getUserInfoBeforeUpdateLoading || updateLoading"
    title="修改客户信息"
    :width="800"
    unit="px"
    @click="replaceTablePopoverVisible = false"
  >
    <el-form
      ref="formInstance"
      class="modal_form_content"
      label-position="top"
      :model="updateForm"
      :rules="rules"
      inline-message
    >
      <el-popover placement="bottom-end" :width="600" :visible="replaceTablePopoverVisible">
        <template #reference>
          <el-form-item label="新客户查询" @click.stop="">
            <div class="new-customer-query">
              <el-input
                v-model.trim="getReplaceCustomersKeyword"
                placeholder="请输入客户名称"
                @keyup.enter="_newCustomerQuery"
              />
              <h-button
                type="primary"
                :loading="getReplaceCustomersLoading"
                @click="_newCustomerQuery"
              >
                搜索
              </h-button>
            </div>
          </el-form-item>
        </template>

        <el-table
          :border="true"
          max-height="300"
          :data="replaceCustomers"
          @row-click="handleReplaceCustomerClick"
        >
          <el-table-column label="序号" width="50" type="index" :align="'center'" />
          <el-table-column show-overflow-tooltip label="客户名称" min-width="100" prop="username" />
          <el-table-column show-overflow-tooltip label="编号" width="120" prop="code" />
          <el-table-column label="手机号" width="110" prop="phone" />
          <!-- <el-table-column show-overflow-tooltip label="省" width="80" prop="province" />
          <el-table-column show-overflow-tooltip label="市" width="80" prop="city" />
          <el-table-column show-overflow-tooltip label="区" width="80" prop="area" />
          <el-table-column show-overflow-tooltip label="详细地址" width="100" prop="address" /> -->
        </el-table>
      </el-popover>

      <!-- 商用：客户名称，家用：店铺/渠道 -->
      <el-form-item :label="productType === 'business' ? '客户名称' : '店铺/渠道'" prop="name">
        <el-input :model-value="updateForm.name" disabled />
      </el-form-item>

      <!-- 客户电话 -->
      <el-form-item v-if="productType === 'business'" label="客户电话" prop="phone">
        <el-input :model-value="updateForm.phone" disabled />
      </el-form-item>

      <!-- 店铺联系方式 -->
      <el-form-item v-if="productType === 'family'" label="店铺联系方式" prop="businessPhone">
        <el-input :model-value="updateForm.businessPhone" disabled />
      </el-form-item>

      <!-- 所属地区 -->
      <el-form-item label="所属地区" prop="province">
        <SingleAddress :address="echoAddress" @change="handleChangeAddress" />
      </el-form-item>

      <!--详细地址-->
      <el-form-item label="详细地址" prop="address">
        <el-input v-model.trim="updateForm.address" />
      </el-form-item>

      <!-- 业务员电话 -->
      <el-form-item v-if="productType === 'business'" class="customer_phone top" label="业务员电话">
        <el-input
          v-model.trim="updateForm.businessPhone"
          maxlength="11"
          placeholder="请输入业务员电话"
          @input="updateForm.businessPhone = updateForm.businessPhone.replace(/[^0-9]/g, '')"
        />
      </el-form-item>

      <!-- 店名 -->
      <el-form-item v-if="productType === 'business'" label="店名">
        <el-input v-model.trim="updateForm.storeName" clearable />
      </el-form-item>

      <!-- 商用：反馈人，家用：联系人 -->
      <el-form-item :label="productType === 'business' ? '反馈人' : '联系人'">
        <el-input v-model.trim="updateForm.sendForRepairUsername" clearable />
      </el-form-item>

      <!-- 商用：反馈电话，家用：联系方式 -->
      <el-form-item :label="productType === 'business' ? '反馈电话' : '联系方式'">
        <el-input
          v-model.trim="updateForm.sendForRepairPhone"
          clearable
          maxlength="11"
          :placeholder="`请输入${productType === 'business' ? '反馈电话' : '联系方式'}`"
          @input="
            updateForm.sendForRepairPhone = updateForm.sendForRepairPhone.replace(/[^0-9]/g, '')
          "
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <h-button is-modal type="primary" @click="onSave">保存</h-button>
      <h-button is-modal @click="close">关闭</h-button>
    </template>
  </h-drawer>
</template>

<style scoped lang="scss">
  .new-customer-query {
    display: flex;
    column-gap: 8px;
    width: 100%;
  }
</style>
